/**
 * 系统视频管理
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, AdvancedSearch, PrimaryC, NoDataC, ModalC, FormGroup, FormItemLayout, UploadC, ContentPackage } from '@/src/components';
import { Row, Modal, Pagination, Spin, message, Form } from 'antd';
import { getTreebyKey } from '@/src/utils/utils';
import { connect } from 'dva';
import style from './index.less';
import CardInfo from './cardInfo';
import config from '../../../utils/enumeratedValues/workStationModuleEnum';

class SystemVedio extends PureComponent {
  state = {
    dataSource: [],
    total: undefined,
    currentPage: 1,
    numInPage: 9,
    searchValue: {}, // 查询条件
    isReset: false, // 是否点击了重置
    isVisible: false,
    currentData: {},
    menuList: [], // 菜单下拉列表
    fileList: [], // 上传文件列表
    loadingStatus: false,
  };

  componentDidMount() {
    this.queryMenuList(); // 查询菜单下拉列表
    this.queryData(); // 查询列表
  }

  // 刷新
  onRefresh = () => {
    this.searchRef.handleReset();
    this.setState(
      {
        fileList: [],
        searchValue: {},
        currentPage: 1,
      },
      () => {
        this.queryData();
      },
    );
  };

  // 查询
  queryData = () => {
    const { searchValue } = this.state;
    this.setState(
      {
        loadingStatus: true,
      },
      () => {
        this.props.dispatch({
          type: 'systemVedioM/queryTableList',
          payload: {
            ...searchValue,
            current: this.state.currentPage,
            pageSize: this.state.numInPage,
          },
          callback: (data) => {
            if (data) {
              this.setState({
                dataSource: data.dataSource || [],
                total: data?.pageInfo?.total || undefined,
                loadingStatus: false,
              });
            } else {
              this.setState({
                dataSource: [],
                total: undefined,
                loadingStatus: false,
              });
            }
          },
        });
      },
    );
  };

  // 查询菜单列表
  queryMenuList = () => {
    this.props.dispatch({
      type: 'systemVedioM/queryMenuList',
      payload: { userId: localStorage.getItem('antd-pro-userId') },
      callback: (data) => {
        if (data) {
          const arr = [...config, ...data];
          arr.map((item) => {
            this.changeMenuList(item);
          });
          this.setState({
            menuList: arr,
          });
        }
      },
    });
  };

  // 将菜单变成value title树形格式
  changeMenuList = (item) => {
    if (item.menuModels && item.menuModels.length) {
      item.value = item.value ? item.value : item.path;
      item.title = item.name;
      item.pageName = item.pageName ? item.pageName : item.name;
      item.selectable = false;
      item.menuModels.map((x) => {
        x.pageName = `${item.pageName}/${x.name}`;
        x.title = x.name;
        x.value = x.menuModels && item.menuModels.length ? `${item.value}/${x.path}` : `/${item.value}/${x.path}`;
        if (x.menuModels && item.menuModels.length) this.changeMenuList(x);
      });
      item.children = item.menuModels;
    } else {
      item.value = item.value ? item.value : `/${item.path}`;
      item.title = item.name;
      item.pageName = item.pageName ? item.pageName : item.name;
    }
  };

  // 每页条数变化
  onShowSizeChange = (current, pageSize) => {
    if (this.state.isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryData();
      },
    );
  };

  // 页码变化
  handlePageChange = (current, pageSize) => {
    if (this.state.isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.queryData();
      },
    );
  };

  // 新增报告
  addVedio = () => {
    this.setState({
      isVisible: true,
    });
  };

  // 编辑报告
  editVedio = (data) => {
    console.log(data);
    this.setState({
      currentData: data,
      fileList: data?.fileList,
      isVisible: true,
    });
  };

  // 删除报告
  deleteVedio = (data) => {
    Modal.confirm({
      title: '确定删除吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: 'systemVedioM/deleteVedio',
          payload: {
            id: data?.id,
          },
          callback: () => {
            this.onRefresh();
          },
        });
      },
    });
  };

  // 取消关闭页面
  onCancel = () => {
    this.setState({
      fileList: [],
      isVisible: false,
      currentData: {},
    });
  };

  onOk = () => {
    const { menuList, fileList, currentData } = this.state;
    this.formRef.getFormGroupData().then((data) => {
      if (!data) return;
      if (!(fileList && fileList.length)) {
        message.warning('请上传附件');
        return;
      }
      const pageUrls = data.businessField;
      const involvedPages = [];
      pageUrls?.map((item) => {
        const tree = getTreebyKey(menuList, item);
        involvedPages.push({
          pageName: tree.pageName,
          pageUrl: item,
        });
      });
      data.businessField = JSON.stringify(involvedPages);
      data.fileList = fileList;
      this.props.dispatch({
        type: 'systemVedioM/addVedio',
        payload: {
          ...data,
          applicationModule: '2',
          id: currentData?.id,
        },
        callback: () => {
          this.onRefresh();
          this.setState({
            fileList: [],
            isVisible: false,
            currentData: {},
          });
        },
      });
    });
  };

  // 获取涉及页面的回填数据
  getPagesId = (arr) => {
    const temp = [];
    arr.map((item) => {
      temp.push(item.pageUrl);
    });
    return temp;
  };

  // 文件上传成功
  onUploadFiles = (files) => {
    console.log(files);
    this.setState({
      fileList: [files],
    });
  };

  render() {
    const { dataSource, total, currentPage, numInPage, isVisible, currentData, menuList, loadingStatus } = this.state;
    const { loading } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['beginDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          allowClear: true,
        },
        {
          dataIndex: 'title',
          title: '标题',
          type: DATA_ENTRY.INPUT,
        },
      ],
      onRef: (ref) => {
        this.searchRef = ref;
      },
      // 点击查询按钮
      onQuery: (e) => {
        if (e.beginDate && e.beginDate != '') e.beginDate = e.beginDate.format('YYYY-MM-DD');
        if (e.endDate && e.endDate != '') e.endDate = e.endDate.format('YYYY-MM-DD');
        this.setState(
          {
            searchValue: e || {},
            isReset: false,
            currentPage: 1,
          },
          () => {
            this.queryData();
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchValue: {},
          isReset: true,
        });
      },
    };
    const modalProps = {
      visible: isVisible,
      destroyOnClose: true,
      onOk: () => {
        this.onOk();
      },
      onCancel: () => {
        this.onCancel();
      },
      title: currentData?.id ? '编辑' : '新增',
      width: 420,
      maskClosable: false,
      confirmLoading: loading.effects['systemVedioM/addVedio'] == true,
    };
    return (
      <ContentPackage
        title='系统视频管理'
        contentHtml={
          <>
            <div style={{ margin: '0 0 20px 0px' }}>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC title='新增' onClick={this.addVedio} style={{ marginBottom: '20px' }} />
            <Spin spinning={loadingStatus}>
              {dataSource && dataSource.length ? (
                <div className={style.cardList}>
                  {dataSource.map((item) => {
                    return <CardInfo itemData={item} key={item.id} editData={this.editVedio} deleteData={this.deleteVedio} />;
                  })}
                </div>
              ) : (
                <NoDataC />
              )}
            </Spin>
            {dataSource && dataSource.length ? (
              <div style={{ float: 'right', padding: '20px 0' }}>
                <Pagination
                  showQuickJumper={true}
                  showSizeChanger={true}
                  onShowSizeChange={this.onShowSizeChange}
                  total={total}
                  showTotal={(total) => `共计 ${total} 条`}
                  pageSize={numInPage}
                  current={currentPage}
                  onChange={this.handlePageChange}
                  pageSizeOptions={['9', '27', '45']}
                />
              </div>
            ) : (
              ''
            )}
            {isVisible ? (
              <ModalC {...modalProps}>
                <div>
                  <FormGroup
                    rowNumber={1}
                    dataSource={[
                      {
                        dataIndex: 'description',
                        title: '标题',
                        type: DATA_ENTRY.INPUT,
                        rules: [{ required: true, message: '请输入标题！' }],
                        initialValue: currentData.description,
                        formItemLayoutDefine: FormItemLayout,
                      },
                      {
                        dataIndex: 'businessField',
                        title: '涉及页面',
                        type: DATA_ENTRY.TREESELECT,
                        rules: [{ required: true, message: '请选择涉及页面！' }],
                        dataSource: menuList || [],
                        isMultiple: true,
                        allowClear: true,
                        positionBody: true,
                        treeDefaultExpandAll: true,
                        initialValue: currentData.businessField ? this.getPagesId(JSON.parse(currentData.businessField)) : undefined,
                        maxTagCount: 0,
                        formItemLayoutDefine: FormItemLayout,
                      },
                    ]}
                    autoLayout={false}
                    onRef={(ref) => {
                      this.formRef = ref;
                    }}
                  />
                  <Form>
                    <Row style={{ paddingRight: '20px', paddingLeft: 1 }}>
                      <Form.Item
                        style={{ width: '100%' }}
                        labelCol={{
                          lg: { span: 7, offset: 0 },
                          xl: { span: 7, offset: 0 },
                          xxl: { span: 7, offset: 0 },
                        }}
                        label='上传视频'
                        name={'fileList'}
                        valuePropName={'fileList'}
                        rules={[{ required: true, message: '请上传视频' }]}
                      >
                        <UploadC
                          type={1}
                          accept={'.mp4,.webm,.ogv'}
                          toolTip={'仅支持上传mp4，webm，ogv'}
                          onRef={(ref) => (this.formUploadRef = ref)}
                          onUpload={(files) => this.onUploadFiles(files)}
                          remove={() => {
                            this.setState({
                              fileList: [],
                            });
                          }}
                          isDowm={false}
                          isDelete={true}
                          max={1}
                          value={currentData.fileList && currentData.fileList.length ? currentData.fileList : null}
                        />
                      </Form.Item>
                    </Row>
                  </Form>
                </div>
              </ModalC>
            ) : (
              ''
            )}
          </>
        }
      />
    );
  }
}
export default connect(({ systemVedio, loading }) => ({ systemVedio, loading }))(SystemVedio);
